<?php
/**
 * @authors alex (20779512@qq.com)
 * @date    2014-03-24 17:25:39
 * @version 1.0
 */

class WeixinAction extends BaseAction {

    public $toUserName;
    public $fromUserName;

    public function _initialize(){
        /*$echoStr = $_GET["echostr"];

        //valid signature , option
        if($this->checkSignature()){
            echo $echoStr;
            exit;
        }*/
        
    }

    //检测签名是否正确返回bool值
    private function checkSignature(){
       
        $signature = $_GET["signature"];
        $timestamp = $_GET["timestamp"];
        $nonce = $_GET["nonce"];
                
        $token = C('token');
        $tmpArr = array($token, $timestamp, $nonce);
        // use SORT_STRING rule
        sort($tmpArr, SORT_STRING);
        $tmpStr = implode( $tmpArr );
        $tmpStr = sha1( $tmpStr );
        
        if( $tmpStr == $signature ){
            return true;
        }else{
            return false;
        }
    }

    public function index(){
        $postStr = $GLOBALS["HTTP_RAW_POST_DATA"];
        $postObj = simplexml_load_string($postStr, 'SimpleXMLElement', LIBXML_NOCDATA);     
        $keyword = trim($postObj->Content);
        $msgType = $postObj->MsgType;
        $EventKey = $postObj->EventKey;
        $eventTime = $postObj->CreateTime;
        $this->toUserName = (string)$postObj->FromUserName;
        $this->fromUserName = (string)$postObj->ToUserName;

        /*$str = '关注事件'.$msgType.'--'.$EventKey;
        $handle = fopen ("1.txt","w");
        if(!fwrite ($handle,$str)){
            die ("生成文件失败！");
        }*/

        #被关注触发回复
        if($msgType=='event'){
            
            $event = $postObj->Event;

            //关注事件
            if ($event=='subscribe') { 

                $access_token = $this->get_access_token();
                $url = 'https://api.weixin.qq.com/cgi-bin/user/info?access_token='.$access_token.'&openid='.$this->toUserName.'&lang=zh_CN';
                $con = file_get_contents($url);
                $con = json_decode($con);

                //检查用户是否存在
                $obj = M('Member');
                $map['wxid'] = (string)$con->openid;
                $list = $obj->where($map)->find();
                if ($list) {
                    //更新是否关注字段
                    $data['wxid']=(string)$con->openid;                    
                    $data['wxface']=(string)$con->headimgurl;
                    $data['wxname']=(string)$con->nickname;
                    $data['guanzhu']=1;
                    $data['createTime']=(int)$eventTime;
                    $obj->where($map)->save($data);
                }else{
                    //添加用户信息
                    if ($EventKey!='' || empty($EventKey)) {
                        //通过二维码过来
                        $data['fid'] = str_replace('qrscene_', '', $EventKey);
                    }else{
                        $data['fid'] = '';
                    }
                    $data['wxid'] = (string)$con->openid;
                    $data['wxname']=(string)$con->nickname;
                    $data['wxface']=(string)$con->headimgurl;
                    $data['guanzhu'] = 1;
                    $data['money'] = C('first_money');
                    $data['createTime'] = (int)$eventTime;
                    if ($data['wxid']!='') {
                        $obj->add($data); 
                    }
                                       
                }

                //关注时自动回复
                $content = '欢迎您【'.$con->nickname.'】关注【'.C('site_name').'】官方微信，感谢您的支持，如您在使用中遇到任何问题，可拨打服务电话'.C('site_tel').'，我们会第一时间为您解答！'."\n".'点击左下方【商城】，开启分享赚钱之旅！';

                
                $this->replyText($content);
            }

            //取消关注
            if ($event == 'unsubscribe') {
                $obj = M('Member');
                $map['wxid'] = (string)$this->toUserName;
                $data['guanzhu']=0;
                $obj->where($map)->save($data);
                setcookie('wxid','');
            }


            //获取推广二维码
            if ($event == 'CLICK') {
                if ($EventKey == '二维码') {
                    $this->makeQrcode();                    
                }
            }
        }


        #普通文本回复
        if($msgType=='text'){
            if (!empty( $keyword )) {
                unset($map);
                $map['name'] = $keyword;
                $map['status'] = 1;
                $list = M('Autoreply')->where($map)->find();
                if ($list) {
                    if ($list['type']==1) { //文本回复
                        $this->replyText($list['text']);
                    }elseif($list['type']==2){ //图文回复
                        $list['article'] = explode(",",$list['article']);
                        unset($map);
                        $map['id']=array('in',$list['article']);
                        $article = M('Article')->field('id,title,intr,picname,url')->where($map)->select();
                        foreach ($article as $key => $value) {
                            if ($value['url']=='') {
                                $article[$key]['url'] = C('site_url').U('News/view',array('id'=>$value['id']));
                            }
                        }                        
                        $this->assign('toUsername',$this->toUserName);
                        $this->assign('fromUsername',$this->fromUserName);
                        $this->assign('time',time());
                        $this->assign('num',count($article));
                        $this->assign('article',$article);
                        $content = $this->fetch("marticle");
                        echo $content;
                    }
                }else{
                    $this->duokefu(); 
                }                          
            }
        }
    }    

    
    #关注时回复
    public function duokefu(){
        $this->assign('toUsername',$this->toUserName);
        $this->assign('fromUsername',$this->fromUserName);
        $this->assign('time',time());
        $this->assign('list',$list);                
        echo $this->fetch('kefu'); 
    }
    
    #文本回复
    public function replyText($content){
        $this->assign('toUsername',$this->toUserName);
        $this->assign('fromUsername',$this->fromUserName);
        $this->assign('time',time());
        $this->assign('content',$content);        
        echo $this->fetch('text');
    }

    #图文回复
    public function replyArticle($title,$description,$picurl,$url){
        $this->assign('toUsername',$this->toUserName);
        $this->assign('fromUsername',$this->fromUserName);
        $this->assign('time',time());
        $this->assign('title',$title);
        $this->assign('description',$description);
        $this->assign('picurl',$picurl);
        $this->assign('url',$url);
        echo $this->fetch('article');
    }


    //生成带参数的二维码
    public function makeQrcode(){
        $map['wxid'] = $this->toUserName;
        $list = M('Member')->where($map)->find();
        if ($list['userGroup']==0 && $list['userType']==0) {
            $content = '亲，购买后方可生成个人专属二维码，获得快乐分享，轻松赚钱资格呦！';
            $this->replyText($content);  
        }else{
            $content = '第一次生成二维码时间较长，请耐心等待20-30秒，尊贵二维码永不失效！如生成失败，请多试几次。';
            $this->replyText($content);  
            $this->reply_customer();  
        }         
    }

    //改变图像尺寸
    function resizeimage($filename){
        // Get new dimensions
        list($width, $height) = getimagesize($filename);
        $new_width = 110;
        $new_height = 110;

        $image_p = imagecreatetruecolor($new_width, $new_height);
        $image = imagecreatefromjpeg($filename);
        imagecopyresampled($image_p, $image, 0, 0, 0, 0, $new_width, $new_height, $width, $height);

        // Output
        imagejpeg($image_p, $filename , 100);
    }
    
    //客服异步回复二维码
    public function reply_customer(){

        $access_token = $this->get_access_token();
        $turePath = 'face/'.$this->toUserName;

        //判断图片是否存在
        if(!file_exists($turePath.'/ewm.jpg')){

            $url = 'https://api.weixin.qq.com/cgi-bin/qrcode/create?access_token='.$access_token;
            $data = '{"action_name": "QR_LIMIT_STR_SCENE", "action_info": {"scene": {"scene_str": "'.$this->toUserName.'"}}}';
            $result = $this->https_post($url,$data);
            $result = json_decode($result);
            $ticket = $result->ticket;
            $ewm = 'https://mp.weixin.qq.com/cgi-bin/showqrcode?ticket='.$ticket;

            //得到用户信息
            $map['wxid'] = (string)$this->toUserName;
            $list = M('Member')->field('wxname,wxface')->where($map)->find();
            if (!$list || $list['wxname']=='') {
                $url = "https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token=".$access_token;
                $data = '{
                    "touser":"'.$this->toUserName.'",
                    "msgtype":"text",
                    "text":
                        {
                             "content":"您的用户信息不完整，暂时不能生成推广二维码，请设置微信昵称和头像。"
                        }
                }';
                $result = $this->https_post($url,$data);
                die;
            }     

            import("@.ORG.Smallpic");
            $faceUrl = $list['wxface'];
            $faceCon = file_get_contents($faceUrl);

            

            if (!is_dir($turePath)) {                
                mkdir($turePath);
            }
            $face = $turePath.'/face.jpg';
            file_put_contents($face,$faceCon); 

            $this->resizeimage($face);

            $pic = new smallpic("bg.jpg");
            $pic->is_text = true;
            $pic->is_ico_pic = true;
            $pic->face_pic = $face;
            $pic->ewm_pic = $ewm;
            $pic->ico_text = "我是".$list['wxname']."!\n这是我的小店欢迎惠顾";
            $pic->face_x = 100;
            $pic->face_y = 30;
            $pic->text_x = 250;
            $pic->text_y = 70;
            $pic->ewm_x = 285;
            $pic->ewm_y = 350;
            $pic->ut = "utf-8";
            $pic->font_color = "#ffffff";
            $pic->big_pic_name = $turePath.'/ewm';
            $pic->createsmallimage();            
        }


        $url = 'http://file.api.weixin.qq.com/cgi-bin/media/upload?access_token='.$access_token.'&type=image';        
        $filePath = $_SERVER['DOCUMENT_ROOT'].'/'.$turePath.'/ewm.jpg';
        $data = array('media' => '@'.$filePath);
        $result = $this->https_post($url,$data);
        $result = json_decode($result);

        $this->assign('toUsername',$this->toUserName);
        $this->assign('fromUsername',$this->fromUserName);
        $this->assign('time',time());
        $this->assign('media_id',$result->media_id);   
                

        $url = "https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token=".$access_token;
        $data = '{
            "touser":"'.$this->toUserName.'",
            "msgtype":"image",
            "image":
                {
                  "media_id":"'.$result->media_id.'"
                }
        }';
        $result = $this->https_post($url,$data);
                
    }


    //生成自定义菜单
    public function makeMenu(){
        $access_token = $this->get_access_token();

        $del = 'https://api.weixin.qq.com/cgi-bin/menu/delete?access_token='.$access_token;
        file_get_contents($del);

        $url='https://api.weixin.qq.com/cgi-bin/menu/create?access_token='.$access_token;
        $data = $this->fetch("menu");

        $ch = curl_init();
        $header = "Accept-Charset: utf-8";
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
        curl_setopt($ch, CURLOPT_SSLVERSION, CURL_SSLVERSION_TLSv1);
        //curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
        curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (compatible; MSIE 5.01; Windows NT 5.0)');
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
        curl_setopt($ch, CURLOPT_AUTOREFERER, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        $tmpInfo = curl_exec($ch);
        $errorno = curl_errno($ch);
        if ($errorno) {
            echo array('rt'=>false,'errorno'=>$errorno);
        }else{
            $js=json_decode($tmpInfo,1);
            if ($js['errcode']=='0'){
                echo array('rt'=>true,'errorno'=>0);
            }else {
                echo '错误代码：'.$js['errcode'].'，errmsg：'.$js['errmsg'];
            }
        }
    }    

}